package com.myebills.ebpsfrontend.cust.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Derive from this class in order to define a servlet that submits, validates, and processes form input.
 * The servlet is run inside a transaction.
 */
public abstract class EbppxSubmitFormServlet extends EbppxTransactionServlet {

    /**
     * Override to validate form input fields
     * and perform whatever transaction may be required when inputs are valid.
     * If any input fields are invalid, add an appropriate message to EbppxInputFieldMessages.
     * By convention, input field messages are indexed by the name of the field.
     */
    protected abstract EbppxInputFieldMessages doFormTransaction(
        HttpServletRequest req,
        HttpServletResponse res)
        throws ServletException;

    /**
     * Validate input form fields, perform required transaction (in doFormTransaction()).
     * If input is valid, dispatch to JSP associated as view.
     * Otherwise, dispatch to referrer with field error messages.
     */
    protected final void doTransaction(
        HttpServletRequest req,
        HttpServletResponse res)
        throws ServletException, java.io.IOException {

        final EbppxInputFieldMessages fieldMsgs = doFormTransaction(req, res);

        if (0 != fieldMsgs.getInputFieldMessageCount()) {
            req.setAttribute(EbppxConstants.EBPPX_INPUT_FIELD_MESSAGES, fieldMsgs);
            forwardToMappedUrl(req, res, EbppxConstants.URL_REFERRER_PARAM);
        } else {
            forwardToMappedUrl(req, res, EbppxConstants.URL_JSP_PARAM);
        }
    }
}